#encoding=utf8
'''
Created on Nov 25, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.db import models
from django import forms

from core.fields import CustomTextField, CustomCharField
from core.widgets import CustomTextarea
import datetime
import settings


SUB_TYPE = (
    ('N', 'New App'),
    ('U', 'Update Existing App'),
)


UPDATE_PURPOSE = (
    ('RAIOR', 'Refresh App Image / Repackage'),
    ('AMGAC', 'Add more Gameplay & Content'),
    ('UAOCP', 'Update Ads / Cross'),
    ('SMOSVAD', 'Support more OS versions & Devices'),
    ('BFAOP', 'Bug Fixes & Optimization'),
    ('OTHER', 'Other'),
)


PREFIX = (
    ('A', 'All'),
    ('I', 'Only Include'),
    ('E', 'Only Exclude'),
)


UPDATE_ASSETS = (
    ('NC', 'No Change'),
    ('UAI', 'Update App Icon'),
    ('US', 'Update Screenshots'),
    ('UFG', 'Update Feature Graphics (Android Only)'),
)


UPDATE_META = (
    ('NC', 'No Change'),
    ('UAN', 'Update App Name'),
    ('UK', 'Update Keywords'),
    ('UAD', 'Update App Description'),
    ('UC', 'Update Category'),
)


RELEASE = (
    ('A', 'Auto Release'),
    ('M', 'Manual Release'),
)


VALIDATION = (
    ('P', 'Pending'),
    ('V', 'Valid'),
    ('I', 'Invalid'),
    ('C', 'Cancelled')
)


BINARY_PRODUCTION_STATUS = (
    ('I', 'In Production'),
    ('R', 'Ready for Upload'),
    ('N', 'N/A'),
)


BINARY_UPLOAD_STATUS = (
    ('W', 'Waiting for Upload'),
    ('U', 'Uploaded'),
    ('N', 'N/A'),
)


SUBMISSION_STATUS = (
#    ('P', 'Preparing'),
    ('Q', 'Queue'),
    ('S', 'Submitted'),
    ('O', 'On Hold'),
    ('C', 'Cancelled'),
)


META_STATUS = (
    ('W', 'Waiting for Upload'),
    ('A', 'All Ready'),
    ('N', 'N/A'),
)


YES_OR_NO = (
    ('Y', 'Yes'),
    ('N', 'No'),
)


RESUB_REQ = (
    ('UBF', u'Send Request to QA Department - select this option if your app submission requires to upload and/or update Binary File'),
    ('UMDAMK', u'Send Request to Marketing Department - select this option if your app submission requires to upload and/or update Meta Data'),
)


SUBINFO_REVIEW_STATUS = (
    ('A', 'Rejected'),
    ('B', 'Pending'),
    ('C', 'Released'),
)


class SubInfo(models.Model):
    request_id = models.CharField(u'Request ID', max_length=20)
    create_time = models.DateTimeField(u'Timestamp', auto_now_add=True)
    editor = models.EmailField(u'Editor', null=True, blank=True)
    app = models.ForeignKey('app_info.App', verbose_name=u'App',
        limit_choices_to={'status': 'V'})
#    type = models.CharField(u'Type', max_length=1, choices=SUB_TYPE, default='N')
#    update_for = models.CharField(u'Update Purpose', max_length=100, null=True,
#        blank=True, default='')
    version = models.CharField(u'App Version', max_length=10)
    is_resub = models.CharField(u'Is Resub?', max_length=1, choices=YES_OR_NO,
        default='N')
#    rej_id = models.CharField(u'Rejection Issue ID', max_length=20, null=True,
#        blank=True, default='')
    rej = models.ForeignKey('Rejection', verbose_name='Rejection', null=True, blank=True)
    resub_req = models.CharField(u'Requests', max_length=30, null=True,
        blank=True, default='')

    edqa = models.DateField(u'Estimate Date of QA', null=True, blank=True)
    etqa = models.CharField(u'Estimate Time of QA', max_length=4, null=True,
        blank=True)
#    programmer = models.CharField(u'Programmer', max_length=20, null=True,
#        blank=True)
    notes_to_qa = CustomTextField(u'Notes to QA', null=True, blank=True,
        default='', widget=CustomTextarea(attrs={'rows': '5',
            'style': '''overflow: hidden; word-wrap: break-word; resize: none;
            width: 400px; height: 46px;'''}))

    edsr = models.CharField(u'Estimated Date of Submission Ready', max_length=20,
        null=True, blank=True, default='')
    price = models.FloatField(u'List Price (USD)', default=0.0)
    prefix = models.CharField(u'Territories', max_length=1, choices=PREFIX, default='A')
    territories = models.TextField(u'Countries', null=True, blank=True, default='')
    update_assets = models.CharField(u'Update on Graphics Assets', max_length=30,
        null=True, blank=True, default='')
    update_meta = models.CharField(u'Update on Meta Data', max_length=30,
        null=True, blank=True, default='')
    rating = models.CharField(u'Suggestion on App Rating', max_length=500,
        null=True, blank=True, default='')
    notes = CustomTextField(u'Special Requirements & Notes', null=True,
        blank=True, default='', widget=CustomTextarea(attrs={'rows': '5',
            'style': '''overflow: hidden; word-wrap: break-word; resize: none;
            width: 400px; height: 46px;'''}))
    release = models.CharField(u'Release Date', max_length=1, choices=RELEASE,
        default='A')

    validation = CustomCharField(u'Validation', max_length=1, choices=VALIDATION,
        null=True, blank=True, default='P',
        widget=forms.Select(attrs={'style': '''width: 100px;'''}))
    valid_date = models.DateField(u'Date - Request Valid', null=True, blank=True)
    validation_notes = CustomTextField(u'Notes', null=True, blank=True, default='',
        widget=CustomTextarea(attrs={'rows': '5', 'style': '''overflow: hidden;
            word-wrap: break-word; resize: none; width: 400px; height: 46px;'''}))

    binary_status = CustomCharField(u'Binary File Ready', max_length=1,
        choices=YES_OR_NO, default='N', null=True, blank=True,
        widget=forms.Select(attrs={'style': '''width: 140px;'''}))
    binary_ready_date = models.DateField(u'Date - Binary File Ready For Upload',
        null=True, blank=True)
    meta_status = CustomCharField(u'Meta Data Ready', max_length=1,
        choices=YES_OR_NO, default='N', null=True, blank=True,
        widget=forms.Select(attrs={'style': '''width: 140px;'''}))
    meta_ready_date = models.DateField(u'Date - All Metadata Uploaded',
        null=True, blank=True)
    binary_upload_status = CustomCharField(u'Binary File Uploaded', max_length=1,
        choices=YES_OR_NO, default='N', null=True, blank=True,
        widget=forms.Select(attrs={'style': '''width: 140px;'''}))
    binary_uploaded_date = models.DateField(u'Date - Binary File Uploaded',
        null=True, blank=True)
    status = CustomCharField(u'Submission Status', max_length=1, null=True, blank=True,
        choices=SUBMISSION_STATUS, default='',
        widget=forms.Select(attrs={'style': '''width: 140px;'''}))
    app_submit_date = models.DateField(u'Date - App Submitted', null=True,
        blank=True, default='')
    sub_person = models.CharField(u'Person - App Submitted', max_length=200,
        null=True, blank=True, default='')

    review_status = models.CharField('Review Status', max_length=1,
        choices=SUBINFO_REVIEW_STATUS, default='B')

    class Meta:
        verbose_name = u'Submission Request'
        verbose_name_plural = u'Submission Request'

    def __unicode__(self):
        return self.request_id

    def get_price(self):
        return "Free" if self.price == 0.0 else str(self.price)

    def get_territories(self):
        return "%s: %s Country" % (self.get_prefix_display(), self.territories) \
            if not self.prefix == 'A' else "All"

    def get_resub_req(self):
        return str(self.resub_req).replace('[', '').replace(']', '').\
            replace("u'", '').replace("'", '').split(', ') if self.resub_req else ""


REVIEW_STATUS = (
    ('PR', 'Pending Review'),
    ('DR', 'Developer Rejected'),
    ('SR', 'App Store Rejected'),
    ('SA', 'App Store Accepted'),
    ('PE', 'Pending Release'),
    ('RE', 'Released'),
)


class ReviewStatus(models.Model):
    sub_info = models.OneToOneField(SubInfo, verbose_name='Submission Request ID')
    status = models.CharField('Review Status', max_length=2, choices=REVIEW_STATUS)
    store_accept_date = models.DateField('Date - App Store Accepted', null=True,
        blank=True)
    release_date = models.DateField('Date - Released', null=True, blank=True)

    class Meta:
        verbose_name = 'Review Status'
        verbose_name_plural = 'Review Status'

    def __unicode__(self):
        return "Review Status of %s" % self.sub_info


class ReviewStatusRecord(models.Model):
    rs = models.ForeignKey(ReviewStatus, verbose_name='Review Status')
    status_before = models.CharField('Status (Before)', max_length=2,
        choices=REVIEW_STATUS, null=True, blank=True)
    status_after = models.CharField('Status (After)', max_length=2,
        choices=REVIEW_STATUS, null=True, blank=True)
    editor = models.CharField('Editor', max_length=100, null=True, blank=True)
    time = models.DateTimeField('Timestamp', auto_now_add=True)

    class Meta:
        verbose_name = ''
        verbose_name_plural = ''
        ordering = ('time',)

    def __unicode__(self):
        return "Status record for %s" % self.rs


ISSUE_STATUS = (
    ('O', 'Open'),
    ('C', 'Closed'),
    ('E', 'Cancelled'),
    ('H', 'On Hold'),
)


class Rejection(models.Model):
    sub_info = models.ForeignKey(SubInfo, verbose_name='Submission Request',
        limit_choices_to={'status': 'S'})
    issue_id = models.CharField('Issue ID', max_length=20)
    editor = models.EmailField('Issue Created By')
    timestamp = models.DateTimeField('Email Received Time', default=datetime.datetime.now)
    status = models.CharField('Issue Status', max_length=1, choices=ISSUE_STATUS,
        default='O')
    create_time = models.DateTimeField('Create Time', auto_now_add=True)

    class Meta:
        verbose_name = 'Rejection'

    def __unicode__(self):
        return self.issue_id


class RejReason(models.Model):
    rej = models.ForeignKey(Rejection, verbose_name='Rejection')
    reason = CustomCharField('Reason', max_length=200,
        widget=forms.TextInput(attrs={'style': '''width: 600px;'''}))
    detail = CustomTextField('Details', null=True, blank=True,
        widget=CustomTextarea)

    class Meta:
        verbose_name = 'Reason of Rejection'
        verbose_name_plural = 'Reason of Rejection'

    def __unicode__(self):
        return 'Rejection Reason of %s' % self.rej


class RejImg(models.Model):
    rej = models.ForeignKey(Rejection, verbose_name='Rejection')
    img = models.ImageField('Screenshot', upload_to=settings.REJ_IMG_DIR,
        null=True, blank=True)
    desc = CustomCharField('Description', max_length=100, null=True, blank=True,
        widget=forms.TextInput(attrs={'style': '''width: 600px;'''}))

    class Meta:
        verbose_name = 'Screenshot'

    def __unicode__(self):
        return 'Rejection Screenshot of %s' % self.rej


class RejAct(models.Model):
    rej = models.ForeignKey(Rejection, verbose_name='Rejection')
    person = models.CharField('Person', max_length=50)
    act = CustomTextField('Action & Results', widget=CustomTextarea)
    date = models.DateField('Date')

    class Meta:
        verbose_name = 'Actions & Results'
        verbose_name_plural = 'Actions & Results'
        ordering = ('-date',)

    def __unicode__(self):
        return 'Actions & Results of %s' % self.rej
